<template>
  <div class="supplier-management">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline @submit.prevent="handleSearch">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="供应商代码">
              <el-input 
                v-model="searchForm.supplierCode" 
                placeholder="请输入供应商代码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商名称">
              <el-input 
                v-model="searchForm.supplierName" 
                placeholder="请输入供应商名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商类型">
              <el-select 
                v-model="searchForm.supplierType" 
                placeholder="请选择供应商类型"
                clearable
                class="full-width-select"
              >
                <el-option 
                  v-for="type in supplierTypes" 
                  :key="type.value"
                  :label="type.label" 
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人姓名">
              <el-input 
                v-model="searchForm.contactName" 
                placeholder="请输入联系人姓名"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select 
                v-model="searchForm.status" 
                placeholder="请选择状态"
                clearable
                class="full-width-select"
              >
                <el-option 
                  v-for="status in supplierStatuses" 
                  :key="status.value"
                  :label="status.label" 
                  :value="status.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <div class="search-buttons">
              <el-button type="primary" @click="handleSearch" :icon="Search">
                搜索
              </el-button>
              <el-button @click="handleReset" :icon="Refresh">
                重置
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 表格标题和操作按钮 -->
    <div class="table-header">
      <div class="table-title">供应商列表</div>
      <div class="table-actions">
        <el-button type="primary" @click="handleAdd" :icon="Plus">
          新增供应商
        </el-button>
        <el-button @click="handleRefresh" :icon="Refresh">
          刷新
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="tableData" 
      class="supplier-table"
      v-loading="tableLoading"
      stripe
      border
      style="width: 100%"
      :fit="true"
    >
      <el-table-column prop="id" label="ID" width="70" align="center" />
      <el-table-column prop="supplierCode" label="供应商代码" width="110" />
      <el-table-column prop="supplierName" label="供应商名称" width="140" />
      <el-table-column prop="supplierType" label="供应商类型" width="110" align="center">
        <template #default="scope">
          <el-tag 
            :type="apiUtils.getSupplierTypeTagType(scope.row.supplierType)"
            :class="'type-tag ' + scope.row.supplierType"
            size="small"
          >
            {{ apiUtils.getSupplierTypeLabel(scope.row.supplierType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="contactName" label="联系人姓名" width="110" />
      <el-table-column prop="contactPhone" label="联系人电话" width="120" />
      <el-table-column prop="address" label="地址" min-width="180" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="90" align="center">
        <template #default="scope">
          <el-tag 
            :type="apiUtils.getStatusTagType(scope.row.status)"
            :class="'status-tag ' + scope.row.status"
            size="small"
          >
            {{ apiUtils.getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" min-width="140" align="center">
        <template #default="scope">
          {{ apiUtils.formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="更新时间" min-width="140" align="center">
        <template #default="scope">
          {{ apiUtils.formatDate(scope.row.updatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleView(scope.row)"
              :icon="View"
            >
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEdit(scope.row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row)"
              :icon="Delete"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.current"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      class="supplier-dialog"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="formData" 
        :rules="formRules" 
        ref="supplierFormRef"
        label-width="120px"
      >
        <el-form-item label="供应商代码" prop="supplierCode">
          <el-input 
            v-model="formData.supplierCode" 
            placeholder="请输入供应商代码"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="formData.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="供应商类型" prop="supplierType">
          <el-select 
            v-model="formData.supplierType" 
            placeholder="请选择供应商类型"
            class="full-width-select"
          >
            <el-option 
              v-for="type in supplierTypes" 
              :key="type.value"
              :label="type.label" 
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="formData.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input v-model="formData.contactPhone" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input 
            v-model="formData.address" 
            type="textarea" 
            :rows="3"
            placeholder="请输入地址"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="formData.status" 
            placeholder="请选择状态"
            class="full-width-select"
          >
            <el-option 
              v-for="status in supplierStatuses" 
              :key="status.value"
              :label="status.label" 
              :value="status.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog 
      v-model="viewDialogVisible" 
      title="供应商详情" 
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="供应商代码">
          {{ currentSupplier.supplierCode }}
        </el-descriptions-item>
        <el-descriptions-item label="供应商名称">
          {{ currentSupplier.supplierName }}
        </el-descriptions-item>
        <el-descriptions-item label="供应商类型">
          <el-tag 
            :type="apiUtils.getSupplierTypeTagType(currentSupplier.supplierType)"
            size="small"
          >
            {{ apiUtils.getSupplierTypeLabel(currentSupplier.supplierType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag 
            :type="apiUtils.getStatusTagType(currentSupplier.status)"
            size="small"
          >
            {{ apiUtils.getStatusLabel(currentSupplier.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系人姓名">
          {{ currentSupplier.contactName }}
        </el-descriptions-item>
        <el-descriptions-item label="联系人电话">
          {{ currentSupplier.contactPhone }}
        </el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">
          {{ currentSupplier.address || '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ apiUtils.formatDate(currentSupplier.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ apiUtils.formatDate(currentSupplier.updatedAt) }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, View, Edit, Delete } from '@element-plus/icons-vue'
import { supplierAPI, apiUtils } from '../utils/api.js'

// 响应式数据
const tableData = ref([])
const tableLoading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)

// 搜索表单
const searchForm = reactive({
  supplierCode: '',
  supplierName: '',
  supplierType: '',
  contactName: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  supplierCode: '',
  supplierName: '',
  supplierType: '',
  contactName: '',
  contactPhone: '',
  address: '',
  status: 'active'
})

// 当前查看的供应商
const currentSupplier = reactive({})

// 下拉选项
const supplierTypes = ref([])
const supplierStatuses = ref([])

// 表单引用
const supplierFormRef = ref(null)

// 表单验证规则
const formRules = apiUtils.getValidationRules()

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑供应商' : '新增供应商'
})

// 方法
const loadSupplierList = async () => {
  try {
    tableLoading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await supplierAPI.getSupplierPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
      pagination.current = response.data.current
      pagination.size = response.data.size
    }
  } catch (error) {
    console.error('加载供应商列表失败:', error)
  } finally {
    tableLoading.value = false
  }
}

const loadSupplierTypes = async () => {
  try {
    const response = await supplierAPI.getSupplierTypes()
    if (response.code === 200) {
      supplierTypes.value = response.data
    }
  } catch (error) {
    console.error('加载供应商类型失败:', error)
  }
}

const loadSupplierStatuses = async () => {
  try {
    const response = await supplierAPI.getSupplierStatuses()
    if (response.code === 200) {
      supplierStatuses.value = response.data
    }
  } catch (error) {
    console.error('加载状态选项失败:', error)
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadSupplierList()
}

const handleReset = () => {
  // 清空搜索表单数据
  Object.keys(searchForm).forEach(key => {
      searchForm[key] = ''
  })
  
  // 重置分页到第一页
  pagination.current = 1
  
  // 重新加载数据
  loadSupplierList()
}

const handleRefresh = () => {
  loadSupplierList()
}

const handleAdd = () => {
  isEdit.value = false
  Object.assign(formData, {
    supplierCode: '',
    supplierName: '',
    supplierType: '',
    contactName: '',
    contactPhone: '',
    address: '',
    status: 'active'
  })
  dialogVisible.value = true
}

const handleView = (row) => {
  Object.assign(currentSupplier, row)
  viewDialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除供应商"${row.supplierName}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await supplierAPI.deleteSupplier(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadSupplierList()
      }
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

const handleSubmit = async () => {
  if (!supplierFormRef.value) return
  
  try {
    await supplierFormRef.value.validate()
    submitLoading.value = true
    
    let response
    if (isEdit.value) {
      response = await supplierAPI.updateSupplier(formData.id, formData)
    } else {
      response = await supplierAPI.addSupplier(formData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
      dialogVisible.value = false
      loadSupplierList()
    }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadSupplierList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadSupplierList()
}

// 生命周期
onMounted(async () => {
  // 先加载下拉选项数据
  await Promise.all([
    loadSupplierTypes(),
    loadSupplierStatuses()
  ])
  
  // 再加载列表数据
  loadSupplierList()
})
</script>

<style scoped>
.supplier-management {
  padding: 20px;
}

.search-form {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.search-form .el-form-item {
  margin-bottom: 15px;
  width: 100%;
}

/* 修复下拉框宽度问题 */
.full-width-select {
  width: 100%;
}

/* 确保下拉框选项宽度足够 */
:deep(.el-select-dropdown) {
  min-width: 200px !important;
}

/* 确保下拉框选项文本可见 */
:deep(.el-select-dropdown__item) {
  white-space: normal;
  height: auto;
  line-height: 1.5;
  padding: 8px 20px;
}

.search-buttons {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.supplier-table {
  border-radius: 6px;
  overflow: hidden;
  width: 100%;
  table-layout: fixed;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  flex-wrap: nowrap;
  gap: 5px;
}

.operation-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 状态标签样式 */
.status-tag.active {
  background-color: #f0f9ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.status-tag.inactive {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffadd6;
}

/* 供应商类型标签 */
.type-tag.material {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.type-tag.equipment {
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.type-tag.service {
  background-color: #f0f5ff;
  color: #1890ff;
  border: 1px solid #adc6ff;
}

.type-tag.other {
  background-color: #fafafa;
  color: #666666;
  border: 1px solid #d9d9d9;
}
</style> 